#include "head.h"

void get_salt(char* salt_val,char* passwd){
    int i,j;
    for(int i=0,j=0;passwd[i]&&j!=3;++i){
        if(passwd[i]=='$'){
            ++j;
        }
    }
    strncpy(salt_val,passwd,i-1);
}
int login(int netfd,char* uname){
    char usrname[1024];
    char password[1024];
    char salt_val[512]={0};
    
    int uerror=2;
    int uerrno=1;
    int name_len=0;
    int pwd_len=0;
    int right=0;

    int times=3;//错误次数
    char MD5_PD_LOCAL[512];
    while(1){
        bzero(usrname,sizeof(usrname));
        bzero(password,sizeof(password));
        if(times==0){//错误次数用完就返回-1
            return -1;
        }
        int retnum= recvn(netfd,&name_len,sizeof(int));
        if(retnum==0){
            printf("断开链接\n");
            return -1;
        }
        recvn(netfd,usrname,name_len);
        recvn(netfd,&pwd_len,sizeof(int));
        recvn(netfd,password,pwd_len);
        
        printf("用户名：%s\n",usrname);
        printf("密码：%s\n",password);
        strcpy(uname,usrname);
        //验证
        //struct spwd* pspwd;
       // pspwd=getspnam(usrname);
        //if(pspwd==NULL){
       //     send(netfd,&uerror,sizeof(int),MSG_NOSIGNAL);
       //     continue;
       // }

       // strcpy(uname,usrname);
        //用salt来验证
      //  strcpy(MD5_PD_LOCAL,pspwd->sp_pwdp);
      //  get_salt(salt_val,pspwd->sp_pwdp);
        //验证
      //  if(strcmp(pspwd->sp_pwdp,crypt(password,salt_val))==0){
      /*      printf("验证成功\n");
            send(netfd,&right,sizeof(int),MSG_NOSIGNAL);
            return 0;
        }
        else{
            printf("验证失败\n");
            send(netfd,&uerrno,sizeof(int),MSG_NOSIGNAL);
            times--;
            continue;
        }
       */
        if(strcmp("ch200319",password)==0){
            printf("验证成功\n");
            send(netfd,&right,sizeof(int),MSG_NOSIGNAL);
            return 0;
        }
        else{
            printf("验证失败\n");
            send(netfd,&uerrno,sizeof(int),MSG_NOSIGNAL);
            times--;
            continue;
        }
    }
    return -1;
}
